package com.heba.fragment.scan;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.product.ItemProductDetailObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫描历史界面
 * <p>
 * Created by jason on 2019/2/20.
 */

public class HistoryScanFragment extends BaseFragment {

    private View view;
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;
    private TextView alertLB;
    private List<ItemProductDetailObject> productObjects = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_history_scan, null);
            initView(view);
        }
        return view;
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onHidden() {
        super.onHidden();
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);
        alertLB = view.findViewById(R.id.alertLB);
        recycleAdapter = new QuickAdapter<ItemProductDetailObject>(productObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_product;
            }

            @Override
            public void convert(VH holder, final ItemProductDetailObject data, int position) {
                GlideUtil.loadImageWithDefaultPlaceHolder(getContext(), data.getIcon(), holder.getView(R.id.img_photo));
                holder.setText(R.id.txt_product, data.getBrandName());
                holder.setText(R.id.txt_content, data.getProductName());
                holder.itemView.setOnClickListener(v -> {
                    Bundle bundle = new Bundle();
                    bundle.putString(CommonConfig.PRODUCT_ID, data.getProductID());
                    openActivity(ItemProductDetailActivity.class, bundle);
                });
            }
        };

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置分隔线
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        //设置增加或删除条目的动画
//        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
                getProductData();
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
                getProductData();
            }
        });
    }

    /**
     * 获取收藏产品
     */
    private void getProductData() {
        if (firstRefresh) {
            firstRefresh = false;
//            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Product/History", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        /**
                         * 判断是否需要清除数据
                         */
                        if (isRefreshFromTop) {
                            if (!productObjects.isEmpty()) {
                                productObjects.clear();
                            }
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }

//                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateProductData(array);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                alertLB.setVisibility(View.VISIBLE);
                                recycleAdapter.notifyDataSetChanged();
//                                ToastShow.displayToast(getActivity(), getResources().getString(R.string.finish_no_data));
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
//                        progressDialog.dismiss();
                        if (isRefreshFromTop) {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }
                    }

                });
    }

    /**
     * updateProductData
     *
     * @param data
     */
    private void updateProductData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductDetailObject productObject = new ItemProductDetailObject();
                productObject.setProductID(object.getString("ProductID"));
                productObject.setProductName(object.getString("ProductName"));
                productObject.setBrandName(object.getString("BrandName"));
                productObject.setCatName(object.getString("CatName"));
                productObject.setIcon(object.getString("Icon"));
                productObjects.add(productObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        recycleAdapter.notifyDataSetChanged();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != view)
            view = null;
    }

}
